import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import gradio as gr

# 加载预训练的transformer模型和tokenizer
model_name = 'Helsinki-NLP/opus-mt-en-zh'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)

def translate(text):
    # 对输入文本进行编码
    inputs = tokenizer.encode(text, return_tensors='pt')

    # 进行翻译
    outputs = model.generate(inputs, max_length=40, num_beams=4, early_stopping=False)
    translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)

    return translated_text

# 创建gradio界面
iface = gr.Interface(fn=translate, inputs='text', outputs='text',description="将英文翻译成中文")
iface.launch()
